package com.acxy.auth.service;

import com.acxy.ants.common.enums.DataSourceType;
import com.acxy.ants.common.kit.StrEncryptKit;
import com.acxy.ants.core.annotation.Service;
import com.acxy.ants.core.annotation.Source;
import com.acxy.ants.core.exception.TipException;
import com.acxy.ants.core.plugin.db.Db;
import com.acxy.auth.common.SysConst;
import com.acxy.auth.entity.User;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017-09-02
 */
@Service
public class SystemService {

    @Source(DataSourceType.DRUID)
    private Db db;

    /**
     * 系统用户登录业务
     *
     * @param username 登录账号
     * @param password 登录密码
     * @param code     验证码
     * @param request  请求对象
     * @return
     */
    public int login(String username, String password, String code, HttpServletRequest request) {
        Object sessionCode = request.getSession().getAttribute(SysConst.CODE_SESSION_NAME);
        if (code == null) throw new TipException("验证码不能为空!");
        User u = new User();
        u.setAccount(username);
        u.setPassword(StrEncryptKit.MD5(password));
        User user = u.find(db);
        if (!code.equalsIgnoreCase(String.valueOf(sessionCode))) return -1;
        if (user == null) return -2;
        //判断账号是否被锁定
        if (user.getIsLock() == 1) return -3;
        //存放session
        request.getSession().setAttribute(SysConst.USER_SESSION_NAME, user);

        //修改登录记录
        u.setLoginCount(user.getLoginCount() + 1);
        u.setLoginIp(request.getRemoteAddr());
        u.setLastLoginTime(new Date());
        return u.update(db);
    }
}
